package org.common.utils.exceltosql;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * 读取xlsx监听处理
 * @author zhouzhibing
 * @date 2024/11/27
 */
class ExcelReadListener extends AnalysisEventListener<Map<Integer, String>> {

    /**
     * 表头数据
     */
    private Map<Integer, String> headMap;
    /**
     * 所有行数据（不包含表头数据）
     */
    private Map<Integer, Map<Integer, String>> allRowMap = new HashMap<>();
    /**
     * 解析处理
     */
    private BiConsumer<Map<Integer, String>, Map<Integer, Map<Integer, String>>> consumer;
    /**
     * 行索引
     */
    private int rowIndex;

    public ExcelReadListener(BiConsumer<Map<Integer, String>, Map<Integer, Map<Integer, String>>> consumer) {
        this.consumer = consumer;
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        this.headMap = ConverterUtils.convertToStringMap(headMap, context);
        this.rowIndex ++;
    }

    @Override
    public void invoke(Map<Integer, String> rowMap, AnalysisContext analysisContext) {
        this.allRowMap.put(rowIndex++ , rowMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(consumer == null)
            return;

        this.consumer.accept(headMap, allRowMap);
    }
}
